import { memo, useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { useNavigate, useLocation, useParams } from 'react-router-dom'
import { Layout, theme, FloatButton, message } from 'antd';
import { LogoutOutlined, RollbackOutlined, UpOutlined, HomeOutlined } from '@ant-design/icons';
import { MemoDocDetailSide } from './component/DocDetailSide';
import { MemoDocDetailHead } from './component/DocDetailHead'
import SimpleEditor from '@/components/Tiptap/tiptap-templates/simple/simple-editor'
import { getDocDetailsByDocId, saveDocMessage } from './component/api';
import styles from './index.module.less';
import { throttle } from '@/utils/debounceThrottle';
import { draftStorage } from '@/utils/storage';

const { Content } = Layout;

const DocDetail = () => {
    // 退出登录功能
    const exit = () => {
        dispatch(showMessage({ message: '退出成功', type: 'success' }))
        dispatch(clearUserInfo())
        clearToken()
        navigate('/login')
    }

    // 返回功能
    const back = () => {
        navigate('/knowledgeBase')
    }

    // 返回首页功能
    const goHome = () => {
        navigate('/')
    }

    const editorRef = useRef();
    // 顶部文档名称
    const [docName, setDocName] = useState('');
    // 编辑器内容（必须为对象）
    const [docContent, setDocContent] = useState({ type: 'doc', content: [] });
    // 权限
    const [docPermission, setDocPermission] = useState('仅阅读');

    // 获取路由参数
    const { id: knowledgeBaseId, docId } = useParams();
    const location = useLocation();
    const navigate = useNavigate();

    const [docListRefreshKey, setDocListRefreshKey] = useState(0);

    // 知识库名称（可选）
    const knowledgeBaseName = location.state?.knowledgeBaseName || '知识库';

    /**
     * 处理左侧文档点击事件
     * 跳转到对应文档详情路由
     */
    const handleDocSelect = (doc) => {
        navigate(`/knowledgeBase/${knowledgeBaseId}/${doc.id}`);
    };

    // 侧边栏文档列表加载完成后，自动跳转到第一条
    const handleDocListLoaded = (docList) => {
        if (docList && docList.length > 0) {
            navigate(`/knowledgeBase/${knowledgeBaseId}/${docList[0].id}`);
        }
    };

    const handleRefreshDocList = () => {
        setDocListRefreshKey(prev => prev + 1);
    };

    // 添加已有文档成功后，刷新侧边栏
    const handleAddExistingDocSuccess = () => {
        handleRefreshDocList();
    };

    /**
     * 监听 docId 变化
     * - 如果是新建文档，重置所有内容
     * - 如果是已有文档，调用接口获取详情并设置
     */
    useEffect(() => {
        async function fetchDraft() {
            if (docId) {
                const draftData = await draftStorage.getDraft(docId);
                if (draftData) {
                    if (draftData.docName) setDocName(draftData.docName);
                    if (draftData.docPermission) setDocPermission(draftData.docPermission);
                    if (draftData.docContent) setDocContent(draftData.docContent);
                    return;
                }
            }
            if (docId) {
                getDocDetailsByDocId(docId).then(res => {
                    if (res && res.code === 200 && res.data) {
                        setDocName(res.data.docName || '未命名文档');
                        let content = '';
                        try {
                            content = res.data.docContent
                                ? (typeof res.data.docContent === 'string'
                                    ? JSON.parse(res.data.docContent)
                                    : res.data.docContent)
                                : { type: 'doc', content: [] };
                        } catch (e) {
                            content = { type: 'doc', content: [] };
                        }
                        setDocContent(content);
                        setDocPermission(res.data.docPermission || '可编辑');
                    } else {
                        setDocName('未命名文档');
                        setDocContent({ type: 'doc', content: [] });
                        setDocPermission('可编辑');
                    }
                });
            }
        }
        fetchDraft();
    }, [docId]);

    // 2. 文档名称、权限或内容变更时自动保存到IndexedDB
    useEffect(() => {
        async function saveDraftAsync() {
            if (docId && docPermission === '可编辑') {
                const draftData = {
                    docName: docName || '未命名文档',
                    docPermission: docPermission,
                    docContent: docContent || { type: 'doc', content: [] }
                };
                await draftStorage.saveDraft(docId, draftData);
            }
        }
        saveDraftAsync();
    }, [docId, docName, docPermission, docContent]);

    // 3. 保存成功后清理草稿的函数
    const clearDraft = async () => {
        if (docId) {
            await draftStorage.removeDraft(docId);
        }
    };

    // 4. 页面卸载时保存草稿（可选，作为额外保障）
    useEffect(() => {
        const handleBeforeUnload = async () => {
            if (docId && docPermission === '可编辑') {
                const draftData = {
                    docName: docName || '未命名文档',
                    docPermission: docPermission,
                    docContent: docContent || { type: 'doc', content: [] }
                };
                await draftStorage.saveDraft(docId, draftData);
            }
        };
        window.addEventListener('beforeunload', handleBeforeUnload);
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [docId, docName, docPermission, docContent]);
    // 新建文档按钮点击事件
    const handleNewDoc = () => {
        navigate(`/knowledgeBase/${knowledgeBaseId}/new`);
        // 跳转后清空编辑器内容
        setTimeout(() => {
            editorRef.current?.clearContent();
            setDocName('未命名文档');
            setDocPermission('可编辑');
        }, 100); // 适当延迟，确保编辑器已挂载
    };

    // 保存
    const handleSave = useCallback(async () => {
        const userId = localStorage.getItem('userId');
        if (!docName || !docContent) {
            message.error('文档名称和内容不能为空！');
            return;
        }
        const params = {
            docName,
            userId,
            docPermission,
            docContent: typeof docContent === 'string' ? docContent : JSON.stringify(docContent),
            isBelongToKnowledgeBase: "1",
            knowledgeBaseId,
        };
        const res = await saveDocMessage(params);
        if (res && res.code === 200) {
            message.success('保存成功！');
            clearDraft(); // 保存成功后清理草稿
            const newDocId = res.data || docId;
            handleRefreshDocList();
            navigate(`/knowledgeBase/${knowledgeBaseId}/${newDocId}`, { state: { refreshDocList: Date.now() } });
        } else {
            message.error('保存失败，请重试！');
        }
    }, [docName, docContent, docPermission, knowledgeBaseId, docId, message, navigate]);
    const throttledSave = useMemo(() => throttle(handleSave, 500), [handleSave]);

    return (
        <Layout className={styles.docDetailLayout} style={{ height: '100vh' }}>
            {/* 右下角浮动按钮 */}
            <FloatButton.Group
                shape="circle"
                trigger="hover"
                type="primary"
                icon={<UpOutlined />}
                style={{
                    insetInlineEnd: 38,
                    insetBlockEnd: 100
                }}
            >
                <FloatButton
                    icon={<LogoutOutlined />}
                    onClick={exit}
                    tooltip="退出登录"
                />
                <FloatButton
                    icon={<RollbackOutlined />}
                    onClick={back}
                    tooltip="返回知识库列表"
                />
                <FloatButton
                    icon={<HomeOutlined />}
                    onClick={goHome}
                    tooltip="返回首页"
                />
            </FloatButton.Group>
            {/* 左侧文档列表 */}
            <MemoDocDetailSide
                knowledgeBaseId={knowledgeBaseId}
                knowledgeBaseName={knowledgeBaseName}
                onDocSelect={handleDocSelect}
                docId={docId}
                onDocListLoaded={handleDocListLoaded}
                refreshKey={docListRefreshKey}
            />
            <Layout>
                <Content className={styles.docDetailContent}>
                    {/* 顶部区域：文档名称、权限按钮等 */}
                    <MemoDocDetailHead
                        docName={docName}
                        setDocName={setDocName}
                        docPermission={docPermission}
                        setDocPermission={setDocPermission}
                        docContent={docContent}
                        knowledgeBaseId={knowledgeBaseId}
                        docId={docId}
                        onSave={throttledSave}
                        onNewDoc={handleNewDoc}
                        onAddExistingDocSuccess={handleAddExistingDocSuccess}
                    />
                    {/* 编辑器区域 */}
                    <Content
                        className={styles.docDetailHeadContent}
                        style={{
                            background: theme.useToken().token.colorBgContainer,
                        }}
                    >
                        <div className={styles.docDetailEditorWrap}>
                            <SimpleEditor
                                ref={editorRef}
                                content={docContent}
                                onContentChange={setDocContent}
                                docId={docId}
                                className={styles.docDetailEditor}
                            />
                            {docPermission === '仅阅读' && (
                                <div
                                    className={styles.docDetailReadMask}
                                    onClick={e => e.preventDefault()}
                                    onMouseDown={e => e.preventDefault()}
                                />
                            )}
                        </div>
                    </Content>
                </Content>
            </Layout>
        </Layout>
    );
}

export const MemoDocDetail = memo(DocDetail)